package com.lzh.runke.core.entity;

import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lzh.runke.core.annotation.operate.Auditable;
import com.lzh.runke.core.annotation.operate.OperatedAt;
import com.lzh.runke.core.annotation.operate.Operator;
import com.lzh.runke.core.web_base.constant.DateConstant;
import com.lzh.runke.core.web_base.helper.BeanHelper;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.SuperBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

import java.io.Serializable;
import java.util.Date;

/**
 * @Description: Entity 基类
 * @Author: LiuZiHao
 * @Date: 2022/5/25 16:03
 */
@Getter
@Setter
@SuperBuilder
@NoArgsConstructor
@Slf4j
@Auditable
public class BaseEntity implements Serializable {

    private static final long serialVersionUID = -277891939915574508L;

    /**
     * 主键
     */
    protected String id;

    /**
     * 创建人
     */
    @Operator
    protected String createBy;

    /**
     * 创建日期
     */
    @OperatedAt
    @JsonFormat(pattern = DateConstant.FMT_YMD)
    protected Date createDate;

    /**
     * 更新人
     */
    @Operator
    protected String updateBy;

    /**
     * 更新日期
     */
    @OperatedAt
    @JsonFormat(pattern = DateConstant.FMT_YMD)
    protected Date updateDate;

    /**
     * 删除标记
     */
    protected Boolean delFlag = false;

    /**
     * 备注
     */
    private String remark;

    //TODO
    /**
     * 数据签名(完整性校验)
     */
    private String dataSign;

    /**
     * 数据签名是否校验通过(完整性校验)
     */
    private Boolean dataSignVerified;

    @JsonAnySetter
    public void handleUnknown(String key, Object value) {
        log.warn("Unknown Property:{{}: {}}", key, value);
    }

    @Override
    public String toString() {
        ObjectMapper om = BeanHelper.getBeanIfAbsent(ObjectMapper.class);
        if (null == om) {
            return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE);
        }
        try {
            return om.writeValueAsString(this);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return super.toString();
    }
}
